/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.apps.controllers;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author ARIJIT PAL
 */
public class DBController {

    private static Connection conn;
    private static String dbString = "jdbc:sqlite:config.db";
    private static String dbClass = "org.sqlite.JDBC";

    public static Connection getConnection() throws Exception {
        if (conn == null || conn.isClosed()) {
            Class.forName(dbClass);
            conn = DriverManager.getConnection(dbString);
        }
        return conn;
    }
    public static List<Map<String,Object>> getResult(String sql)throws Exception{
        Connection connL = getConnection();
        Statement stat = connL.createStatement();
        ResultSet rs = stat.executeQuery(sql);
        List<Map<String,Object>> output = new ArrayList<Map<String, Object>>();
        while(rs.next()){
            Map<String, Object> data = new HashMap<String, Object>();
            int columnCount = rs.getMetaData().getColumnCount();
            for(int i=1; i<=columnCount; i++){
                String columnName = rs.getMetaData().getColumnName(i);
                String value = rs.getString(i);
                data.put(columnName, value);
            }
            output.add(data);
        }
        rs.close();
        return output;
    }
    public static int updateData(String sql) throws Exception{
        System.out.println(sql);
        Connection connL = getConnection();
        Statement stat = connL.createStatement();
        return stat.executeUpdate(sql);
    }
}
